// 用户登录
const { MongoClient, ServerApiVersion } = require('mongodb')
let dayjs = require('dayjs')
const { generateToken } = require('../utils/getToken')

// 数据库地址
const uri = 'mongodb://localhost:27017/libraryDB'

// 连接数据库
const client = new MongoClient(uri, {
  serverApi: {
    version: ServerApiVersion.v1,
    strict: true,
    deprecationErrors: true,
  },
})

// 用户登录查询
const userLogin = async (contactNumber, password) => {
  try {
    await client.connect()
    // 获取数据库对象
    const db = client.db('libraryDB')
    // 获取student_info表
    const studentInfoDb = db.collection('users')
    const res = await studentInfoDb.findOne(contactNumber, password)
    console.log(contactNumber, password)

    if (res) {
      // 生成Token
      const token = generateToken(res)
      // 将Token添加到用户文档中
      await studentInfoDb.updateOne(
        { _id: res._id },
        { $set: { token: token } }
      )
      return {
        msg: '登录成功',
        time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        msgCode: 10000,
        data: {
          token,
          role: res.role,
          success: true,
        },
      }
    } else {
      return {
        msg: '手机号或者密码错误',
        time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        msgCode: 10002,
        data: {
          success: false,
        },
      }
    }
  } catch (error) {
    console.log(error)
    return {
      msg: '服务器异常',
      success: false,
    }
  } finally {
    client.close()
  }
}
module.exports = { userLogin }
